package com.controller;

import com.entity.MaintenanceAreaLevel2;
import com.service.MaintenanceAreaLevel2Service;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/maintenance/area/level2")
public class MaintenanceAreaLevel2Controller {

    @Autowired
    private MaintenanceAreaLevel2Service maintenanceAreaLevel2Service;

    @PostMapping
    public MaintenanceAreaLevel2 create(@RequestBody MaintenanceAreaLevel2 maintenanceAreaLevel2) {
        return maintenanceAreaLevel2Service.save(maintenanceAreaLevel2);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable(value = "id") Integer id) {
        maintenanceAreaLevel2Service.deleteById(id);
    }

    @PutMapping("/{id}")
    public MaintenanceAreaLevel2 update(@PathVariable(value = "id") Integer id, @RequestBody MaintenanceAreaLevel2 maintenanceAreaLevel2) {
        maintenanceAreaLevel2.setId(id);
        return maintenanceAreaLevel2Service.save(maintenanceAreaLevel2);
    }

    @GetMapping("/{id}")
    public MaintenanceAreaLevel2 detail(@PathVariable(value = "id") Integer id) {
        return maintenanceAreaLevel2Service.findById(id).orElse(null);
    }

    @GetMapping("/page")
    public Page<MaintenanceAreaLevel2> page(@RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "10") int pageSize,
                       @RequestParam(required = false) String areaName) {
        Page<MaintenanceAreaLevel2> page;
        if (areaName != null && !areaName.isEmpty()) {
            page = maintenanceAreaLevel2Service.findByAreaNameContaining(areaName, pageNum, pageSize);
        } else {
            page = maintenanceAreaLevel2Service.findAll(pageNum, pageSize);
        }
        return page;
    }
}